// routes/blogRoutes.js
const express = require('express');
const router = express.Router();
const blogModel = require('../controllers/bolgControll');
const upload = require('../controllers/uploadConfig');
const jwtBlacklistControll = require('../controllers/jwtBlacklistControll');
const path = require('path');
const fs = require('fs');
const { expressjwt: expressJwt } = require('express-jwt');
const key = "Yangjunjwt123456"; // 秘钥
// 获取用户通过JWT中的ID
router.get('/profile', expressJwt({ secret: key, algorithms: ['HS256'] }), async (req, res) => {
  try {
    const userId = req.auth.userId; // 从JWT中提取用户ID
    console.log("BlogRouteruserid"+userId);
    const blog = await blogModel.getBlogByUserid(userId);
    if (blog) {
      res.json(blog);
    } else {
      res.status(404).json({ message: '用户不存在' });
    }
  } catch (error) {
    if (error.name === 'UnauthorizedError') {
      // 将无效的 JWT 添加到黑名单中
      const token = req.headers.authorization.split(' ')[1];
      await jwtBlacklistControll.addTokenToBlacklist(token);
      res.status(401).json({ message: '未携带token或token失效' });
    } else {
      res.status(500).json({ message: error.message });
    }
  }
});
router.get('/:id', async (req, res) => {
  try {
    const blog = await blogModel.getBlogById(req.params.id);
    if (blog) {
      res.json(blog);
    } else {
      res.status(404).json({ message: 'Blog nottt found' });
    }
  } catch (error) {
    res.status(500).json({ message: error.message });
  }
});


// router.get('/', async (req, res) => {
//   try {
//     const blogs = await blogModel.getAllBlogs();
//     res.json(blogs);
//   } catch (error) {
//     res.status(500).json({ message: error.message });
//   }
// });
// 获取博客列表（支持关键字查询）
router.get('/', async (req, res) => {
  const { keyword = '' } = req.query;
  try {
  console.log("关键字"+keyword);
    const blogs = await blogModel.getAllBlogs(keyword);
    res.json({ blogs });
  } catch (error) {
    res.status(500).json({ message: error.message });
  }
});

// 获取博客列表（带分页）
// router.get('/bolgPage', async (req, res) => {
//   const { page = 1, pageSize = 10 } = req.query;
//   try {
//     const { blogs, totalCount } = await blogModel.getBlogsByPage(page, pageSize);
//     res.json({ blogs, totalCount });
//   } catch (error) {
//     res.status(500).json({ message: error.message });
//   }
// });
router.post('/add', expressJwt({ secret: key, algorithms: ['HS256'] }),async (req, res) => {
  try {
    const user_id = req.auth.userId; // 从JWT中提取用户ID
    const {  title, content } = req.body;
    const blogId = await blogModel.createBlog(user_id,  title, content);
    res.status(201).json({ blogId });
  } catch (error) {
    if (error.name === 'UnauthorizedError') {
      // 将无效的 JWT 添加到黑名单中
      const token = req.headers.authorization.split(' ')[1];
      await jwtBlacklistControll.addTokenToBlacklist(token);
      res.status(401).json({ message: '未携带token或token失效' });
    } else {
      res.status(500).json({ message: error.message });
    }
  }
});

router.put('/:id', async (req, res) => {
  try {
    const { title, content } = req.body;
    await blogModel.updateBlog(req.params.id, title, content);
    res.json({ message: 'Blog updated successfully' });
  } catch (error) {
    res.status(500).json({ message: error.message });
  }
});

router.delete('/:id', async (req, res) => {
  try {
    await blogModel.deleteBlog(req.params.id);
    res.json({ message: 'Blog deleted successfully' });
  } catch (error) {
    res.status(500).json({ message: error.message });
  }
});
// 文件上传路由
router.post('/upload', upload.single('file'), async (req, res) => {
  try {
    const { blog_id } = req.body;
    const file = req.file;

    if (!file) {
      return res.status(400).json({ message: 'No file uploaded' });
    }

    // 保存文件信息到数据库
    await blogModel.addAttachment(blog_id, file.filename, file.path);

    res.status(200).json({ message: 'File uploaded successfully', file: file });
  } catch (error) {
    res.status(500).json({ message: error.message });
  }
});
// router.post('/upload', upload.single('file'), (req, res) => {
//   try {
//     const filePath = req.file.path.replace(/\\/g, '/');
//     res.json({
//       message: 'File uploaded successfully',
//       file: {
//         ...req.file,
//         path: filePath
//       }
//     });
//   } catch (error) {
//     res.status(500).json({ message: 'File upload failed', error: error.message });
//   }
// });
// 文件下载路由
router.get('/download/:filename', (req, res) => {
  const filename = req.params.filename;
  const filePath = path.join(__dirname, '..', 'public', 'loads', filename);

  if (fs.existsSync(filePath)) {
    res.download(filePath);
  } else {
    res.status(404).json({ message: 'File not found' });
  }
});
router.get('/attach/:blogId', async (req, res) => {
  try {
    const attachments = await blogModel.getAttachmentsByBlogId(req.params.blogId);
    res.json(attachments);
  } catch (error) {
    res.status(500).json({ message: error.message });
  }
});
module.exports = router;
